package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.IntegralAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.IntegralModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/6/13.
 */

public class IntegralFragment extends Fragment implements CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.OnRefreshListener, ResultSubscriber.OnResultListener {

    private static final int REFRESH_MODE = 0x01;
    private static final int LOAD_MORE_MODE = 0x02;

    protected Context mContext;
    protected View contentView;
    protected CanRefreshLayout refreshLayout;
    protected JpRefreshView footerView;
    protected RecyclerView recyclerView;

    protected int type;
    protected List<IntegralModel.ListBean> integralModelList;
    protected IntegralAdapter adapter;

    private String cachePath;
    private FileCacheManager cacheManager;

    public static IntegralFragment newInstance(int type){
        IntegralFragment fragment = new IntegralFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(this.mContext != null)
            return;

        this.mContext = getContext();
        this.type = getArguments().getInt("type");

        contentView = View.inflate(mContext, R.layout.refresh_recycleview, null);
        refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
        footerView = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);
        recyclerView = (RecyclerView) contentView.findViewById(R.id.can_content_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setHasFixedSize(true);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        integralModelList = new ArrayList<>();
        adapter = new IntegralAdapter(mContext, integralModelList);
        StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(adapter);
        recyclerView.addItemDecoration(headersDecor);
        recyclerView.setAdapter(adapter);
        adapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {

            }
        });

        cachePath = mContext.getCacheDir() + "/integral";
        UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
        if(userData != null)
            cachePath += ("_" + userData.getUuid());
        cachePath += ("_"  + type + ".dat");
        cacheManager = new FileCacheManager();

        readCache();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return contentView;
    }

    public void autoRefresh(){
        refreshLayout.autoRefresh();
    }

    @Override
    public void onRefresh() {
        getData(-1);
    }

    @Override
    public void onLoadMore() {
        if(footerView.isLoadComplete())
            onCompleted(LOAD_MORE_MODE);
        else if(integralModelList.size() > 0)
            getData(integralModelList.get(integralModelList.size()-1).getDateTime());
        else
            onRefresh();
    }

    public void getData(long time){
        JsonObject param = new JsonObject();
        if(time > 0)
            param.addProperty("time", time);
        param.addProperty("type", type);
        HttpHelper.getInstance(mContext).integralHistory(param, time < 0 ? REFRESH_MODE : LOAD_MORE_MODE, this);
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<IntegralModel.ListBean>>() {
            @Override
            public void call(Subscriber<? super List<IntegralModel.ListBean>> subscriber) {
                List<IntegralModel.ListBean> data = (List<IntegralModel.ListBean>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<IntegralModel.ListBean>>() {
            @Override
            public void onCompleted() {
                autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<IntegralModel.ListBean> data) {
                if(data != null) {
                    integralModelList = data;
                    adapter.updateAdapter(integralModelList);
                }
                onCompleted();
            }
        });
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_MODE)
            refreshLayout.refreshComplete();
        else
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_MODE || requestType == LOAD_MORE_MODE) {
            if(requestType == REFRESH_MODE) {
                footerView.setLoadComplete(false);
                integralModelList.clear();
            }
            List<IntegralModel.ListBean> integralModels = null;
            IntegralModel model = data.getEntity(IntegralModel.class);
            if(model != null)
                integralModels = model.getList();
            if (integralModels != null && integralModels.size() > 0) {
                for (IntegralModel.ListBean integralModel : integralModels)
                    integralModel.setShowTime(model.getDateTime());
                integralModelList.addAll(integralModels);
            } else if(requestType == LOAD_MORE_MODE){
                footerView.setLoadComplete(true);
            }
            adapter.updateAdapter(integralModelList);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    cacheManager.wirteObject(integralModelList, cachePath);
                }
            }).start();
        }
    }
}
